package ruifeng.zcj.dig.ui.forum;

import android.Manifest;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;
import de.hdodenhof.circleimageview.CircleImageView;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
import ruifeng.zcj.dig.R;
import ruifeng.zcj.dig.base.api.ApiHttpClient;
import ruifeng.zcj.dig.ui.forum.bean.NewPost;
import ruifeng.zcj.dig.ui.forum.bean.NewPostDetail;
import ruifeng.zcj.mybase.base.BaseFragment;
import ruifeng.zcj.mybase.base.utils.GlideUtil;

/**
 * 帖子的内容，在帖子详情中的顶部
 * Created by Administrator on 2016/10/12 0012.
 */
public class ForumContentFragment extends BaseFragment implements BGANinePhotoLayout.Delegate {

    protected String content;
    protected ForumDetailActivity mForumDetailActivity;
    protected NewPost.RowsBean mRowsBean;


    private static final int REQUEST_CODE_PERMISSION_PHOTO_PREVIEW = 1;


    @Bind(R.id.activity_top_left)
    ImageView mActivityTopLeft;
    @Bind(R.id.activity_top_center)
    TextView mActivityTopCenter;
    @Bind(R.id.activity_top_right)
    ImageView mActivityTopRight;
    @Bind(R.id.activity_top_right_text)
    TextView mActivityTopRightText;
    @Bind(R.id.vehicle_fragment_item_img)
    CircleImageView mVehicleFragmentItemImg;
    @Bind(R.id.vehicle_fragment_item_price1)
    TextView mVehicleFragmentItemPrice1;
    @Bind(R.id.vehicle_fragment_item_price)
    TextView mVehicleFragmentItemPrice;

    @Bind(R.id.vehicle_fragment_item_title)
    TextView mVehicleFragmentItemTitle;
    @Bind(R.id.tv_item_moment_username)
    TextView mTvItemMomentUsername;
    @Bind(R.id.npl_item_moment_photos)
    BGANinePhotoLayout mNplItemMomentPhotos;
    @Bind(R.id.color_name)
    TextView mColorName;
    @Bind(R.id.color)
    View mColor;
    @Bind(R.id.forum_plate)
    TextView mForumPlate;
    @Bind(R.id.forum_fragment_title)
    TextView mForumFragmentTitle;
    @Bind(R.id.left_name)
    TextView mLeftName;
    @Bind(R.id.right_name)
    TextView mRightName;

    /****
     * 当前的mCurrentClickNpl
     **/
    private BGANinePhotoLayout mCurrentClickNpl;

    /**
     * 配置eventbus
     **/
    protected void initUIConfig(FragmentConfig fragmentConfig) {
        fragmentConfig.isApplyEventBus = true;
    }

    @Override
    protected void initFragmentConfig(View view) {
        mForumDetailActivity = (ForumDetailActivity) mActivity;
        mActivityTopCenter.setText("帖子详情");
        mLeftName.setText("浏览量");
        mRightName.setText("评论");


        //   mNplItemMomentPhotos.setData(moment.photos);
//        mForumDetailActivity.mNewPostDetail


    }

    protected void setContent() {
        GlideUtil.loadImage(getContext(), "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png", mVehicleFragmentItemImg);
        mVehicleFragmentItemTitle.setText("" + mRowsBean.getUsername());// 名称
        mVehicleFragmentItemPrice1.setText("" + mRowsBean.getTime());// 发帖时间
        mForumPlate.setText("" + mRowsBean.getCnfirstsection() + "" + mRowsBean.getCnsecondsection());// 板块名称
        mForumFragmentTitle.setText("" + mRowsBean.getPostingsname());// 帖子标题
        mTvItemMomentUsername.setText("" + mRowsBean.getPostingscontent());// 帖子内容文字
        mLeftName.setText("浏览量" + mRowsBean.getViews());
        mRightName.setText("评论" + mRowsBean.getComment());
    }

    //
    @Override
    protected int getContentView() {
        return R.layout.fragment_forum_content;
    }

    @Override
    protected synchronized void activityCreate() {
        super.activityCreate();
        showSnackBar("运行到这了");
    }

    @Override
    protected void onFirstUserVisible() {
        showSnackBar("运行到这了onFirstUserVisible");
        mRowsBean = mForumDetailActivity.getRowsBean();
        if (mRowsBean != null) {
            setContent();
        }

    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    protected void cleanMemory() {

    }

    /**
     * 与发布者在同一个线程
     * 注意事项：
     * 1.事件被post后哪个事件的监听者会响应的问题，这个取决于你写的监听方法所跟的参数类型。
     * 2.你写的事件监听方法得是public修饰的，如果你写成private了，则不会收到消息。
     * 3.如果你所有的事件监听方法都不用public修饰（包括父类），则会直接报错：
     *
     * @param content 事件2
     */
    @Subscribe
    public void onEvent(String content) {
        this.content = content;
        if (!TextUtils.isEmpty(content)) {
            showSnackBar("还有一个吊丝评论了你");
        }
    }

    /**
     * 与发布者在同一个线程
     * 注意事项：
     * 1.事件被post后哪个事件的监听者会响应的问题，这个取决于你写的监听方法所跟的参数类型。
     * 2.你写的事件监听方法得是public修饰的，如果你写成private了，则不会收到消息。
     * 3.如果你所有的事件监听方法都不用public修饰（包括父类），则会直接报错：
     *
     * @param mNewPostDetail 事件2
     */
    @Subscribe
    public void onEvent(NewPostDetail mNewPostDetail) {
        if (mNewPostDetail != null) {
            if (mNewPostDetail.getPostingsdetail().size() > 0) {
                mNplItemMomentPhotos.init(mForumDetailActivity);
                mNplItemMomentPhotos.setDelegate(this);
                mForumDetailActivity.getNewPostDetail();
                ArrayList<String> urlArray = new ArrayList<>();
                ArrayList<String> type = new ArrayList<>();
                for (int i = 0; i < mNewPostDetail.getPostingsdetail().size(); i++) {
                    NewPostDetail.PostingsdetailBean posting = mNewPostDetail.getPostingsdetail().get(i);
                    urlArray.add(ApiHttpClient.getAbsoluteApiUrl(posting.getUrl()));
                    type.add(posting.getType());
                }
                mNplItemMomentPhotos.setData(urlArray);
            }
        }
    }


    // 点击图片查看图片
    @Override
    public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
        mCurrentClickNpl = ninePhotoLayout;
        photoPreviewWrapper();
    }

    /**
     * 图片预览，兼容6.0动态权限
     */
    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PREVIEW)
    private void photoPreviewWrapper() {
        if (mCurrentClickNpl == null) {
            return;
        }

        // 保存图片的目录，改成你自己要保存图片的目录。如果不传递该参数的话就不会显示右上角的保存按钮
        File downloadDir = new File(Environment.getExternalStorageDirectory(), "zcj");

        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            if (mCurrentClickNpl.getItemCount() == 1) {
                // 预览单张图片: null   mDownLoadableCb.isChecked() ?
                startActivity(BGAPhotoPreviewActivity.newIntent(getContext(), downloadDir, mCurrentClickNpl.getCurrentClickItem()));
            } else if (mCurrentClickNpl.getItemCount() > 1) {
                // 预览多张图片 mDownLoadableCb.isChecked() ?  : null
                startActivity(BGAPhotoPreviewActivity.newIntent(getContext(), downloadDir, mCurrentClickNpl.getData(), mCurrentClickNpl.getCurrentClickItemPosition()));
            }
        } else {
            EasyPermissions.requestPermissions(this, "图片预览需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PREVIEW, perms);
        }
    }

    @Override
    public boolean onLongClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
        showSnackBar("长按了图片" + position);
        return true;
    }

    public ForumDetailActivity getForumDetailActivity() {
        if (mForumDetailActivity != null) return mForumDetailActivity;
        else return mForumDetailActivity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
